<?php

/*

	WebPhrame - A rudimentary PHP web site framework
	Copyright (c) 2008 Joshua Bodine

	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU Lesser General Public License as
	published by the Free Software Foundation, either version 3 of the
	License, or (at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU Lesser General Public License for more details.

	You should have received a copy of the GNU Lesser General Public
	License along with this program.  If not, see
	<http://www.gnu.org/licenses/>.

*/

class Auth {
	public $id, $name, $priv;
	private $users, $history;

	public function __construct($users, $history, Auth $last = null) {
		$this->users = $users;
		$this->history = $history;

		if($last && $last->id) {
			$this->id = $last->id;
			$this->priv = $users->getPrivLevel($this->id);
			$this->name = $users->getUserName($this->id);
		} else {
			$this->id = 0;
			$this->priv = 0;
		}
	}

	public function isLoggedIn() {
		if($this->id)
			return true;

		return false;
	}

	public function logIn($name, $password) {
		$id = $this->users->getUserID($name);

		if($this->users->checkPassword($password, $id)) {
			$this->id = $id;
			$this->priv = $this->users->getPrivLevel($id);
			$this->name = $this->users->getUserName($this->id);

			$_SESSION['auth'] = $this;

			$this->history->log($this->id, "login", $_SERVER['REMOTE_ADDR']." (".gethostbyaddr($_SERVER['REMOTE_ADDR']).")");

			return true;
		}

		return false;
	}

	public function logOut() {
		$this->history->log($this->id, "logout", $_SERVER['REMOTE_ADDR']." (".gethostbyaddr($_SERVER['REMOTE_ADDR']).")");

		unset($this->id);
		unset($this->priv);

		unset($_SESSION['auth']);
	}
}

?>
